package com.weipu.common.facade.content.api;

import java.util.ArrayList;
import android.content.ContentValues;
import android.database.Cursor;
import com.weipu.common.DXApplication;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.content.BaseService;
import com.weipu.common.facade.content.ContentURI;
import com.weipu.common.facade.content.colum.CategoryColumn;
import com.weipu.common.facade.model.CatelogModel;
import com.weipu.common.util.Logger;

/**
 * 栏目数据操作接口封装
 *
 * @author zhl014
 */
public class CategoryService extends BaseService {
    // /**
    // * Logger for this class
    // */
    // private static final Logger logger = Logger
    // .getLogger(CategoryService.class);

    private static final String TAG = CategoryService.class.getName();

    /**
     * 保存栏目信息(异步)
     *
     * @param category 栏目信息对象{@link CatelogModel}
     */
    public boolean saveCategoryInfo(CatelogModel category) {
        if (Logger.isLog) {
            Logger.d("saveCategoryInfo(CatelogModel) - start, category: "
                    + (null == category ? "null" : category.getShortName()));
        }

        ContentValues initialValues = new ContentValues();

        // Model与values转换
        initialValues.put(CategoryColumn.CATEGORY_ID, category.getBrowseID());
        initialValues.put(CategoryColumn.NAME, category.getShortName());
        initialValues.put(CategoryColumn.PARENT_ID, category.getParentId());

        if (0 == category.getCacheUpdateTime()) {
            initialValues.put(CategoryColumn.UPDATE_TIME, System.currentTimeMillis());
        } else {
            initialValues.put(CategoryColumn.UPDATE_TIME, category.getCacheUpdateTime());
        }

        boolean isSuccess = false;

        try {
            DXApplication.getContext()
                    .getContentResolver()
                    .insert(ContentURI.CategoryList.CONTENT_URI_ALL, initialValues);
            isSuccess = true;
        } catch (Exception e) {
            Logger.e(TAG, "saveCategoryInfo error.", e);
        }

        if (Logger.isLog) {
            Logger.d("saveCategoryInfo(CatelogModel) - end, isSuccess: " + isSuccess);
        }
        return isSuccess;
    }

    /**
     * 根据栏目ID删除对应数据
     *
     * @param categoryID 栏目ID
     */
    public int deleteCategoryInfoByID(String categoryID) {
        if (Logger.isLog) {
            Logger.d("deleteCategoryInfoByID(String) - start, categoryID: " + categoryID);
        }

        String selection = CategoryColumn.CATEGORY_ID + "=?";
        String[] selectionArgs = {categoryID};

        int returnint =
                DXApplication.getContext()
                        .getContentResolver()
                        .delete(ContentURI.CategoryList.CONTENT_URI_ALL, selection, selectionArgs);
        if (Logger.isLog) {
            Logger.d("deleteCategoryInfoByID(String) - end, categoryID: " + categoryID);
        }
        return returnint;
    }

    /**
     * 根据父栏目ID删除子栏目列表
     *
     * @param parentCategoryID 父栏目ID
     */
    public int deleteCategoryListByParentID(String parentCategoryID) {
        if (Logger.isLog) {
            Logger.d("deleteCategoryListByParentID(String) - start, parentCategoryID: " + parentCategoryID);
        }

        String selection = CategoryColumn.PARENT_ID + "=?";
        String[] selectionArgs = {parentCategoryID};

        int returnint =
                DXApplication.getContext()
                        .getContentResolver()
                        .delete(ContentURI.CategoryList.CONTENT_URI_ALL, selection, selectionArgs);
        if (Logger.isLog) {
            Logger.d("deleteCategoryListByParentID(String) - end,returnint: " + returnint);
        }
        return returnint;
    }

    /**
     * 删除所有栏目数据
     */
    public int clearCategory() {
        if (Logger.isLog) {
            Logger.d("clearCategory() - start");
        }

        int returnint =
                DXApplication.getContext().getContentResolver().delete(ContentURI.CategoryList.CONTENT_URI_ALL, null, null);
        if (Logger.isLog) {
            Logger.d("clearCategory() - end, returnint: " + returnint);
        }
        return returnint;

    }

    /**
     * 查询栏目信息对象 如果存在多个则默认返回第一个(根据数据Row ID升序 )
     *
     * @param categoryID 栏目ID
     */
    public CatelogModel queryCategoryDetailByCategoryID(String categoryID) {
        if (Logger.isLog) {
            Logger.d("queryCategoryDetailByCategoryID(String) - start, categoryID: " + categoryID);
        }

        String[] projection = CategoryColumn.QUERY_PROJECTION;

        String selection = CategoryColumn.CATEGORY_ID + "=?";
        Cursor cursor = null;
        CatelogModel returnCatelogModel = null;
        try {
            cursor =
                    DXApplication.getContext()
                            .getContentResolver()
                            .query(ContentURI.CategoryList.CONTENT_URI_ALL,
                                    projection,
                                    selection,
                                    new String[]{categoryID},
                                    null);

            returnCatelogModel = parseModel(cursor);
        } catch (Exception e) {
            Logger.e(TAG, "queryCategoryDetailByCategoryID error.", e);
        } finally {
            close(cursor);
        }
        if (Logger.isLog) {
            Logger.d("queryCategoryDetailByCategoryID(String) - end, returnCatelogModel: " + returnCatelogModel);
        }
        return returnCatelogModel;

    }

    // 解析栏目对象
    private CatelogModel parseModel(Cursor c) {

        if (null == c || c.getCount() < 1) {
            return null;
        }

        c.moveToFirst();

        CatelogModel returnCatelogModel = getSingleModel(c);
        return returnCatelogModel;
    }

    /**
     * 查询指定目录下子目录列表
     *
     * @param parentCategoryID 栏目ID
     */
    public ArrayList<CatelogModel> queryCategoryListByParentCategoryID(String parentCategoryID) {
        if (Logger.isLog) {
            Logger.d("queryCategoryListByParentCategoryID(String) - start, parentCategoryID: " + parentCategoryID);
        }

        String[] projection = CategoryColumn.QUERY_PROJECTION;

        String selection = CategoryColumn.PARENT_ID + "=?";
        Cursor cursor = null;
        ArrayList<CatelogModel> returnArrayList = null;
        try {
            cursor =
                    DXApplication.getContext()
                            .getContentResolver()
                            .query(ContentURI.CategoryList.CONTENT_URI_ALL,
                                    projection,
                                    selection,
                                    new String[]{parentCategoryID},
                                    null);

            returnArrayList = parseModelList(cursor);

        } catch (Exception e) {
            Logger.e(TAG, "queryCategoryListByParentCategoryID error.", e);
        } finally {
            close(cursor);
        }
        if (Logger.isLog) {
            Logger.d("queryCategoryListByParentCategoryID(String) - end, returnArrayList: "
                    + (null != returnArrayList ? returnArrayList.size() : "0"));
        }
        return returnArrayList;

    }

    private CatelogModel getSingleModel(Cursor c) {

        CatelogModel model = new CatelogModel();
        model.setBrowseID(c.getInt(0));
        model.setShortName(c.getString(1));
        model.setParentId(c.getString(2));
        model.setCacheUpdateTime(c.getLong(3));
        return model;
    }

    // 解析栏目列表
    private ArrayList<CatelogModel> parseModelList(Cursor c) {
        if (Logger.isLog) {
            Logger.d("parseModelList(Cursor) - start");
        }

        if (null == c || c.getCount() < 1) {
            if (Logger.isLog) {
                Logger.d("parseModelList(Cursor) - end");
            }
            return null;
        }

        c.moveToFirst();

        if (Logger.isLog) {
            Logger.i("parseModelList(Cursor) - count: " + c.getCount());
        }

        ArrayList<CatelogModel> result = new ArrayList<CatelogModel>(c.getCount());

        do {
            result.add(getSingleModel(c));

        } while (c.moveToNext());

        if (Logger.isLog) {
            Logger.d("parseModelList(Cursor) - end");
        }
        return result;
    }
}
